package com.example.springsecuritydemo.test;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class Main5 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        //一个线程
        sum1();

        //4个线程
        sum2();


    }

    public static void sum1() throws ExecutionException, InterruptedException {
        long startTime = System.currentTimeMillis();
        Run run = new Run(1L, 6000000000L);
        FutureTask<Long> futureTask = new FutureTask<>(run);
        new Thread(futureTask).start();
        Long sum = futureTask.get();
        System.out.println(sum);
        long endTIme = System.currentTimeMillis();
        System.out.println("timeUsed: " + (endTIme - startTime) + "毫秒");
    }

    public static void sum2() throws ExecutionException, InterruptedException {
        long startTime = System.currentTimeMillis();
        Run run1 = new Run(1L, 1000000000L);
        FutureTask<Long> futureTask1 = new FutureTask<>(run1);
        new Thread(futureTask1).start();

        Run run2 = new Run(1000000001L, 2000000000L);
        FutureTask<Long> futureTask2 = new FutureTask<>(run2);
        new Thread(futureTask2).start();

        Run run3 = new Run(2000000001L, 3000000000L);
        FutureTask<Long> futureTask3 = new FutureTask<>(run3);
        new Thread(futureTask3).start();

        Run run4 = new Run(3000000001L, 4000000000L);
        FutureTask<Long> futureTask4 = new FutureTask<>(run4);
        new Thread(futureTask4).start();

        Run run5 = new Run(4000000001L, 5000000000L);
        FutureTask<Long> futureTask5 = new FutureTask<>(run5);
        new Thread(futureTask5).start();

        Run run6 = new Run(5000000001L, 6000000000L);
        FutureTask<Long> futureTask6 = new FutureTask<>(run6);
        new Thread(futureTask6).start();

        Long sum1 = futureTask1.get();


        Long sum2 = futureTask2.get();


        Long sum3 = futureTask3.get();


        Long sum4 = futureTask4.get();


        Long sum5 = futureTask5.get();


        Long sum6 = futureTask6.get();

        System.out.println(sum1 + sum2 + sum3 + sum4 + sum5 + sum6);

        long endTIme = System.currentTimeMillis();
        System.out.println("timeUsed: " + (endTIme - startTime) + "毫秒");
    }
}

class Run implements Callable<Long> {

    private final Long num1;
    private final Long num2;

    public Run(Long num1, Long num2) {
        this.num1 = num1;
        this.num2 = num2;
    }

    @Override
    public Long call() {
        System.out.println(System.currentTimeMillis());
        long sum = 0;
        for (long i = num1; i <= num2; i++) {
            sum += i;
        }
        return sum;
    }
}
